package ru.spb.osll.myfit.server.chart;

import org.jfree.chart.ChartFactory;
import org.jfree.chart.ChartUtilities;
import org.jfree.chart.JFreeChart;
import org.jfree.chart.plot.PlotOrientation;
import org.jfree.chart.plot.XYPlot;
import org.jfree.chart.renderer.xy.XYItemRenderer;
import org.jfree.data.xy.DefaultTableXYDataset;
import org.jfree.data.xy.XYDataset;
import org.jfree.data.xy.XYSeries;
import ru.spb.osll.myfit.common.chart.ChartCurve;
import ru.spb.osll.myfit.common.chart.ChartPoint;

import java.awt.*;
import java.io.ByteArrayOutputStream;
import java.io.IOException;

public class BasePngChartRenderer implements ChartRenderer {

  @Override
  public byte[] render(ChartRenderData data) throws IOException {
    XYDataset dataset = createDataset(data);
    JFreeChart chart = ChartFactory.createXYLineChart(
            data.getTitle(),                                        // chart title
            data.getHorizontalLabel(),                              // domain axis label
            data.getVerticalLabel(),                                // range axis label
            dataset,                                                // data
            PlotOrientation.VERTICAL,                               // orientation
            true,                                                   // include legend
            true,                                                   // tooltips
            false                                                   // urls
    );
    chart.setBackgroundPaint(data.getBackgroundColor());
    XYPlot plot = (XYPlot) chart.getPlot();
    XYItemRenderer renderer = plot.getRenderer();
    setColors(data, renderer);

    plot.setBackgroundPaint(data.getBackgroundColor());
    plot.setRangeGridlinePaint(data.getGridColor());
    ByteArrayOutputStream stream = new ByteArrayOutputStream();
    ChartUtilities.writeChartAsPNG(stream, chart, data.getWidth(), data.getHeight());
    stream.flush();
    byte[] renderedChart = stream.toByteArray();
    stream.close();
    return renderedChart;
  }

  private void setColors(ChartRenderData data, XYItemRenderer renderer) {
    int i = 0;
    for (ChartCurve curve : data.getCurves()) {
      renderer.setSeriesPaint(i++, new Color(curve.getColor()));
    }
  }

  private XYDataset createDataset(ChartRenderData data) {
    DefaultTableXYDataset dataset = new DefaultTableXYDataset();
    for (ChartCurve curve : data.getCurves()) {
      XYSeries series = new XYSeries(curve.getName(), true, false);
      for (ChartPoint point : curve.getPoints()) {
        series.add(point.getX(), point.getY());
      }
      dataset.addSeries(series);
    }
    return dataset;
  }
}